package com.tzy.rpc.codec;/**
 * @description:
 * @Author HP
 * @create 2022/3/14 20:40
 */

import com.tzy.rpc.entity.RpcRequest;
import com.tzy.rpc.enumeration.PackageType;
import com.tzy.rpc.serializer.CommonSerializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author HP
 * @create 2022-03-14 20:40
 * @desc 编码器
 **/
public class CommonEncoder extends MessageToByteEncoder {

    private static final Logger logger= LoggerFactory.getLogger(CommonEncoder.class);

    private static final int MAGIC_NUMBER = 0xCAFEBABE;

    private final CommonSerializer serializer;

    public CommonEncoder(CommonSerializer serializer){
        this.serializer=serializer;
        logger.info("序列化器使用： {}",serializer.getClass().getName());
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        out.writeInt(MAGIC_NUMBER);
        if (msg instanceof RpcRequest){
            out.writeInt(PackageType.REQUEST_PACK.getCode());
        }else {
            out.writeInt(PackageType.RESPONSE_PACK.getCode());
        }
        out.writeInt(serializer.getCode());
        byte[] bytes = serializer.serialize(msg);
        out.writeInt(bytes.length);
        out.writeBytes(bytes);
    }
}
